package com.kelp.codetoolkit.utils

import com.intellij.database.util.common.isNotNullOrEmpty
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.modules
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.wm.WindowManager
import com.intellij.psi.*
import com.kelp.codetoolkit.utils.frame.SpringUtil
import java.awt.Window


/**
 * @author: liuyuebai
 * @date: 2024/9/10 18:55
 * @description:
 */
object ProjectUtil {

    /**
     * 获取当前module
     */
    fun getModule(project: Project,moduleName:String): Module? {
        val moduleManager = ModuleManager.getInstance(project)
        return moduleManager.findModuleByName(moduleName)
    }

    fun getModule(psiJavaFile: PsiJavaFile): Module? {
        val project = psiJavaFile.project
        return ProjectFileIndex.getInstance(project).getModuleForFile(psiJavaFile.virtualFile)
    }

    /**
     * 可能存在多个，本方法只能项目存在两个字module
     */
    fun getServiceModule(project: Project): Module? {
        project.modules.forEach { module->
            if (module.name != project.name) {
                val applicationPath = SpringUtil.getSpringBootApplicationPath(module)
                if (applicationPath.isNotNullOrEmpty){
                    return module
                }
            }
        }
        return null
    }


    fun getProjectSubModules(project: Project):List<Module>{
        val moduleList = ModuleManager.getInstance(project).modules
        val newModuleList = moduleList.filter { module -> module.name != project.name }
        return newModuleList
    }

    fun getCurrentContext(element: PsiElement): PsiElement {
        var context = element
        // 向上查找，获取当前所在的类或方法上下文（可根据需求调整，比如也关注接口等 ）
        while (context.parent != null && context !is PsiFile) {
            if (context is PsiClass || context is PsiMethod) {
                return context
            }
            context = context.parent
        }
        return element
    }
}